﻿using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.EntityFrameworkCore;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Globalization;

namespace RearLivestock.Beginning.Api.Application.Command.Farrowing
{
    public class ImportFarrowingHandler : IRequestHandler<ImportFarrowingCommand, Result>
    {
        /// <summary>
        /// 母猪分娩仓储
        /// </summary>
        private readonly IBaseRepository<Farrowings> farrowingsRepository;
        /// <summary>
        /// 基本信息耳号仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        /// 栋舍分类信息仓储
        /// </summary>
        private readonly IBaseRepository<BedroomTypes> bedroomTypesRepository;
        /// <summary>
        /// 批次仓储
        /// </summary>
        private readonly IBaseRepository<Batchs> batchsRepository;
        /// <summary>
        /// 分娩难易
        /// </summary>
        private readonly IBaseRepository<Difficulties> difficultiesRepository;
        /// <summary>
        /// 母性
        /// </summary>
        private readonly IBaseRepository<Maternals> maternalsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="farrowingsRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="bedroomTypesRepository"></param>
        /// <param name="batchsRepository"></param>
        /// <param name="difficultiesRepository"></param>
        /// <param name="maternalsRepository"></param>
        public ImportFarrowingHandler(IBaseRepository<Farrowings> farrowingsRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<BedroomTypes> bedroomTypesRepository, IBaseRepository<Batchs> batchsRepository, IBaseRepository<Difficulties> difficultiesRepository, IBaseRepository<Maternals> maternalsRepository)
        {
            this.farrowingsRepository = farrowingsRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.bedroomTypesRepository = bedroomTypesRepository;
            this.batchsRepository = batchsRepository;
            this.difficultiesRepository = difficultiesRepository;
            this.maternalsRepository = maternalsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(ImportFarrowingCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //获取文件扩展名 判断上传的文件类型是否正确
                var ext = Path.GetExtension(request.file.FileName);
                if (ext == ".xls" || ext == ".xlsx")
                {

                }
                else
                {
                    result.Msg = "您上传的文件类型不正确";
                    return result;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    request.file.CopyTo(ms);
                    ms.Position = 0;

                    //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                    //获取工作簿
                    IWorkbook wb = null;
                    if (ext == ".xls")//创建97-2003
                    {
                        wb = new HSSFWorkbook(ms);
                    }
                    else//创建2007及以上版本
                    {
                        wb = new XSSFWorkbook(ms);
                    }

                    //获取sheet 获取工作簿中的第一个工作表
                    ISheet sheet = wb.GetSheetAt(0);

                    int totalRows = sheet.LastRowNum;//总行数
                    int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                    // 创建一个用于存储解析后的数据的列表
                    var farrowingsList = new List<Farrowings>();

                    //循环总行数 开头必须是1 不然从表头开始
                    //遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
                    for (int i = 1; i <= totalRows; i++)
                    {
                        //获取当前行
                        IRow row = sheet.GetRow(i);

                        //这个类必须写到循环里边 不然你批量添加只能添加一行
                        var dto = new Farrowings();// 在循环内创建新的对象实例

                        //下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
                        var earnumber = row.GetCell(0).ToString();
                        var basic = await (await basicInformationRepository.GetAll()).Where(z => z.EarNumber == earnumber).FirstOrDefaultAsync();
                        dto.BasicInforId = basic.BasicInforId;

                        //日期转换
                        //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                        string inputDate = row.GetCell(1).ToString();
                        string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
                        DateTime parsedDate;
                        foreach (var format in multipleFormats)
                        {
                            if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                            {
                                dto.FarrowingDate = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
                                break;//成功解析后跳出循环
                            }
                        }

                        dto.GestationNum = Convert.ToInt32(row.GetCell(2).ToString());
                        dto.DifficultieId = Convert.ToInt32(row.GetCell(3).ToString());
                        dto.BatchId = Convert.ToInt32(row.GetCell(4).ToString());
                        dto.MaternalId = Convert.ToInt32(row.GetCell(5).ToString());
                        dto.Lactation = row.GetCell(6).ToString();
                        dto.Mastitis = row.GetCell(7).ToString();
                        dto.NestNumber = row.GetCell(8).ToString();
                        dto.LivePigNum = Convert.ToInt32(row.GetCell(9).ToString());
                        dto.NestWeight = Convert.ToInt32(row.GetCell(10).ToString());
                        dto.Gender = row.GetCell(11).ToString() == "男" ? 1 : 0;
                        dto.BedroomId = Convert.ToInt32(row.GetCell(12).ToString());
                        dto.FieldId = Convert.ToInt32(row.GetCell(12).ToString());
                        dto.TurnBuilding = row.GetCell(14).ToString();
                        dto.TurnColumn = row.GetCell(15).ToString();
                        dto.IsFarrowings = Convert.ToInt32(row.GetCell(16).ToString());

                        //添加到数据集合中
                        farrowingsList.Add(dto);
                    }
                    //跳出循环后 使用AddRange进行批量添加
                    var res = farrowingsRepository.AddRange(farrowingsList);
                    //判断
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "导入成功";
                    }
                    else
                    {
                        result.Msg = "导入失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "导入异常" + ex.Message;
            }
            return result;
        }
    }
}
